/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.network.tcp.tests;

import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.junit.Test;
import org.latestbit.smartobjects.network.IConnection;
import org.latestbit.smartobjects.network.IStreamListener;

class PerfListener implements IStreamListener {
	public final Lock asyncConditionLock = new ReentrantLock();
	public final Condition asyncCondition = asyncConditionLock.newCondition();
	public int nRcvdCnt = 0;
	public int nRcvdBytes = 0;
	
	@Override
	public void onWriteError(IConnection connection, String errorMessage) {
	}
	
	@Override
	public void onReceived(IConnection connection, ByteBuffer buffer) {
		asyncConditionLock.lock();
		nRcvdCnt++;
		nRcvdBytes+= (buffer.limit() - buffer.position());
		asyncCondition.signal();		
		asyncConditionLock.unlock();
	}
	
	@Override
	public void onReceiveError(IConnection connection, String errorMessage) {
	}
}

public class TCPSyncPacketExchangeTest {
	
	@Test
	public void testSyncPacketExchangePerf() throws Exception {
		URI serverURI = new URI("tcp://localhost:3336");
		TCPTestServer server = new TCPTestServer(serverURI);
		TCPTestClient client = new TCPTestClient(serverURI);
		
		server.getAcceptor().start();
		server.getListener().getConditionLock().lock();		
		client.getConnector().connect();
		server.getListener().waitCondition();
		server.getListener().getConditionLock().unlock();
	
		client.getConnector().delConnectionListener(client.getListener());
		client.getConnector().delStreamListener(client.getListener());
		IConnection serverConnection = server.getListener().getAcceptedConnections().iterator().next();
		serverConnection.addStreamListener(new IStreamListener() {


			@Override
			public void onReceiveError(IConnection connection, String errorMessage) {}

			@Override
			public void onWriteError(IConnection connection, String errorMessage) {}

			@Override
			public void onReceived(IConnection connection, ByteBuffer buffer) {
				try {
					connection.send(buffer);
				}
				catch(Exception ex) {
					ex.printStackTrace();
				}
			}

			
		});
		
		PerfListener perfListener = new PerfListener();
		client.getConnector().addStreamListener ( 
				perfListener
		);

		final ByteBuffer sendBuffer = ByteBuffer.allocate(5);
		sendBuffer.put(new byte[] { 0x0A, 0x0B, 0x0C, 0x0D, 0x0E });
		
		long startTime, endTime, progressTime1, progressTime2, 
			tps = 0, maxTps = 0, minTps = Long.MAX_VALUE, midTps = 0, sntBytes = 0,
			totalSent = 0, totalRcvd = 0;
		
        startTime = Calendar.getInstance().getTimeInMillis();        
        progressTime1 = startTime;
        progressTime2 = startTime;
        final int PRF_ITER_SYNC_CNT = 100000;
		
		for(int i=0; i<PRF_ITER_SYNC_CNT; i++, tps++) {
			sendBuffer.flip();
			perfListener.asyncConditionLock.lock();
			client.getConnector().send(sendBuffer);
			perfListener.asyncCondition.await();			
			perfListener.asyncConditionLock.unlock();
			progressTime1 = Calendar.getInstance().getTimeInMillis();
			sntBytes+=sendBuffer.position();
			totalSent+=sendBuffer.position();
			if(progressTime1 > progressTime2 + 1000) {
				perfListener.asyncConditionLock.lock();
				System.out.println("TPS/Rcvd: "+tps+"/"+perfListener.nRcvdCnt+". Bytes: "+sntBytes+"/"+perfListener.nRcvdBytes);
				perfListener.nRcvdCnt = 0;				
				totalRcvd+=perfListener.nRcvdBytes;
				perfListener.nRcvdBytes = 0;
				sntBytes = 0;
				perfListener.asyncConditionLock.unlock();
				progressTime2 = progressTime1;
				if(maxTps<tps)
					maxTps = tps;
				if(minTps>tps && i > PRF_ITER_SYNC_CNT / 10)
					minTps = tps;
				midTps+= tps;
				tps = 0;
			}			
		}
        endTime = Calendar.getInstance().getTimeInMillis();
        midTps = (long) (midTps / ((endTime-startTime)/1000.0));
        System.out.println("Elapsed time for sync model: "+ ((endTime-startTime)/1000.0)+". Mid. Resp. Time: "+(endTime-startTime)/PRF_ITER_SYNC_CNT+". Max TPS: "+maxTps+". Min TPS: "+minTps+". Mid TPS: "+midTps);

        client.getConnector().close();
		server.getAcceptor().stop();
	}
}
